package org.kmfdm.horrorscope.tapestry.pages.user;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.kmfdm.horrorscope.core.spring.ApplicationContextProviderSingleton;
import org.kmfdm.horrorscope.metamodel.Customer;
import org.kmfdm.horrorscope.metamodel.User;
import org.kmfdm.horrorscope.service.Login;

import org.kmfdm.horrorscope.tapestry.pages.Info;
import org.springframework.context.ApplicationContext;

public class LoginUser {

	@SessionState 
	private User user;
	

	@Inject
	private Login login;
	@InjectPage
	private Info info;
	
	private String username;
	private String password;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	@Component(id="userLogin")	
	private Form userLoginForm;
	
	private ApplicationContext applicationContext(){
		return new ApplicationContextProviderSingleton().getContext();
	}
	private Customer createCustomer(){
		return (Customer) applicationContext().getBean(Customer.class.getName());
	}
	
	public User getUser() {
		if(user==null){
			user=createUser();
		}
		
		return user;
	}
	private User createUser() {
		return (User) applicationContext().getBean(User.class.getName());
		
	}
	public void setUser(User user) {
		this.user = user;
	}
	
	
	@OnEvent(component="userLogin")
	public Object onSuccess(){
		user = (User)login.login(username, password);
		if(user!=null) 	
			info.setMessage("Welcome, "+user.getUsername() +"!");
		else info.setMessage("Login failed, wrong username/password");
		return info;
		
	}
	
}
